var obj = {
    qCRuleId: "",
    qCRuleSourceId: "",
    qCRuleExpression: "",
    qCRuleCompare: "yes",
    qCRuleSourceCompare: "yes",
    qcTableID: ""
};
var flag = 0;
$(function () {
    $.parser.parse(); // 解析整个页面

    $HUI.combobox('#QCDic',
        {
            data: $.parseJSON($("#entityMap").val()),
            valueField: 'value',
            textField: 'text',
            onSelect: obj.entityChange,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                $(this).combobox("setValue", val[0].value);
            }
        })

    $HUI.combobox('#linkCdss',
        {

            valueField: 'value',
            textField: 'text',
            multiple: true,
            rowStyle: 'checkbox', //显示成勾选行形式
            selectOnNavigation: false,
            //panelHeight:"auto",
            editable: false
        })

    if (flag == 0) {
        obj.entityChange();
    }
})

obj.entityChange = function (that) {

    obj.qCTable.clearSelections();
    obj.ClearForms();
    obj.qcTableID = "";

    var ajax = new $ax(Sys.backendPath + "/sdc/sdcqcconfig/selectQcByEntityId", function (data) {
        $('#qCTable').datagrid({loadFilter: pagerFilter}).datagrid('loadData', data);
    }, function (data) {
        layer.msg("查询失败!" + data.responseJSON.message + "!", {icon: 2});
    });
    ajax.set({"qcentityId": Common_GetValue('QCDic')});
    ajax.start();

    var entityId = Common_GetValue('QCDic');

    var ajax2 = new $ax(Sys.backendPath + "/sdc/sdcqcconfig/getCdssMapByEntityId", function (data) {
        $('#linkCdss').combobox({
            data: data,
            valueField: 'value',
            textField: 'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    }, function (data) {
        layer.msg("查询失败!" + data.responseJSON.message + "!", {icon: 2});
    });
    ajax2.set({"entityId": entityId});
    ajax2.start();
}

obj.qCChange = function () {
    var ajax = new $ax(Sys.backendPath + "/sdc/sdcqcconfig/selectQcRuleByExpression", function (data) {
        $('#qCRule').datagrid({loadFilter: pagerFilter}).datagrid('loadData', data);
    }, function (data) {
        layer.msg("查询失败!" + data.responseJSON.message + "!", {icon: 2});
    });
    ajax.set({"id": Common_GetValue('QCDic')});
    ajax.set({"displayRule": encodeURIComponent(Common_GetValue('qcExpression'))});
    ajax.set({"compare": obj.qCRuleCompare});
    ajax.start();
}

obj.qCRuleChange = function () {
    var ajax = new $ax(Sys.backendPath + "/sdc/sdcqcconfig/selectQcRuleDataSourceByExpression", function (data) {
        $('#qCRuleDataSource').datagrid({loadFilter: pagerFilter}).datagrid('loadData', data);
    }, function (data) {
        layer.msg("查询失败!" + data.responseJSON.message + "!", {icon: 2});
    });
    ajax.set({"ruleExpressions": obj.qCRuleExpression});
    ajax.set({"compare": obj.qCRuleSourceCompare});
    ajax.start();
}

// 初始化质控条目表格
obj.qCTable = $HUI.datagrid("#qCTable", {
    fit: true,
    pagination: true, //如果为true, 则在DataGrid控件底部显示分页工具栏
    displayMsg: "当前表格显示 {from} 到 {to} ,共 {total} 条记录",
    singleSelect: true,
    //定义是否设置基于该行内容的行高度。设置为 false，则可以提高加载性能
    autoRowHeight: false,
    striped: true,
    rownumbers: true,
    loadMsg: '数据加载中...',
    pageSize: 10,
    pageList: [10, 50],
    idField: "id",
    columns: [[
        {field: 'qcDesc', title: '描述', width: '300', align: 'left', sortable: false}
    ]]
    , onClickRow: function (rowIndex, rowData) {
    }
    , onLoadSuccess: function (rowData) {

    },
    onSelect: function (rowIndex, rowData) {
        if (rowIndex > -1) {
            obj.gridQCTable_onSelect(rowData);
        }
    }
});

obj.gridQCTable_onSelect = function (rowData) {
    if (obj.qcTableID != rowData.id) {
        $("#qcDesc").val(rowData.qcDesc);
        $("#qcExpression").val(rowData.qcExpression);
        $("#expDescription").val(rowData.expDescription);
        $("#qcMemo").val(rowData.qcMemo);
        $("#qcId").val(rowData.id);
        $('#linkCdss').combobox('setValues', rowData.linkCdss.split("#"));//多选
        $('#activeOnce').checkbox('setValue', rowData.activeOnce == 1 ? true : false);
        $('#isActive').checkbox('setValue', rowData.isActive == 1 ? true : false);
        $('#isBox').checkbox('setValue', rowData.isBox == 1 ? true : false);
        $("#source").val(rowData.source);
        $('#vteType').val(rowData.type);
        obj.qCChange();

        obj.qcTableID = rowData.id
    } else {
        obj.qCTable.clearSelections();
        obj.ClearForms();
        obj.qcTableID = "";
    }
}

obj.ClearForms = function () {
    $("#qcDesc").val('');
    $("#qcExpression").val('');
    $("#expDescription").val('');
    $("#qcMemo").val('');
    $("#qcId").val('');
    $('#linkCdss').combobox('setValues', '');//多选
    $('#activeOnce').checkbox('setValue', '');
    $("#source").val('');
    $('#vteType').val('');
    $('#isActive').checkbox('setValue', '');
    $('#isBox').checkbox('setValue', '');
    obj.qCChange();
}

obj.qCRule = $HUI.datagrid("#qCRule", {
    fit: true,
    pagination: true, //如果为true, 则在DataGrid控件底部显示分页工具栏
    displayMsg: "当前表格显示 {from} 到 {to} ,共 {total} 条记录",
    singleSelect: true,
    checkOnSelect: true,
    //定义是否设置基于该行内容的行高度。设置为 false，则可以提高加载性能
    autoRowHeight: false,
    striped: true,
    rownumbers: true,
    loadMsg: '数据加载中...',
    pageSize: 10,
    pageList: [10, 50],
    idField: "id",
    columns: [[
        // {field: 'expCode', title: '代码', width: '80', align: 'left', sortable: false},
        // /*{field:'ruleExpression',title:'表达式',width:'200',align:'left',sortable:false},
        // {field:'ruleParm',title:'参数',width:'200',align:'left',sortable:false},*/
        // {field: 'ruleCal', title: '规则', width: '200', align: 'left', sortable: false},
        // {field: 'ruleType', title: '计算类型', width: '200', align: 'left', sortable: false},
        // {field: 'ruleDesc', title: '规则描述', width: '200', align: 'left', sortable: false},
        // {field: 'ruleMemo', title: '备注', width: '300', align: 'left', sortable: false},
        {field: 'ruleCode', title: '编码', width: '100', align: 'left', sortable: false},
        {field: 'ruleDesc', title: '规则名称', width: '320', align: 'left', sortable: false},
        {field: 'comment', title: '备注', width: '320', align: 'left', sortable: false},
        {field: 'ruleType', title: '规则类型', width: '200', align: 'left', sortable: false},
        {field: 'calType', title: '计算类型', width: '200', align: 'left', sortable: false},
        {field: 'isDefault', title: '默认值', width: '200', align: 'left', sortable: false,formatter:function (value, row, index){
                if (value == 1) {
                    return "<span class='label label-success'>true</span>";
                } else {
                    return "<span class='label label-warning'>false</span>";
                }}
        },
    ]]
    , onClickRow: function (rowIndex, rowData) {
        obj.qCRuleId = rowData.id;
        //obj.qCRuleExpression = encodeURIComponent(rowData.ruleExpression);
        //obj.qCRuleChange();
    }
    , onLoadSuccess: function (rowData) {
    }
});

obj.qCRuleDataSource = $HUI.datagrid("#qCRuleDataSource", {
    fit: true,
    pagination: true, //如果为true, 则在DataGrid控件底部显示分页工具栏
    displayMsg: "当前表格显示 {from} 到 {to} ,共 {total} 条记录",
    singleSelect: true,
    checkOnSelect: true,
    //定义是否设置基于该行内容的行高度。设置为 false，则可以提高加载性能
    autoRowHeight: false,
    striped: true,
    rownumbers: true,
    loadMsg: '数据加载中...',
    pageSize: 10,
    pageList: [10, 50],
    idField: "id",
    columns: [[
        {field: 'code', title: '代码', width: '80', align: 'left', sortable: false},
        {field: 'dataSource', title: '取值来源', width: '200', align: 'left', sortable: false},
        {field: 'dataSourceItem', title: '取值项目', width: '200', align: 'left', sortable: false},
        {
            field: 'havePar',
            title: '是否需要传参',
            width: '200',
            align: 'left',
            sortable: false,
            formatter: function (value, row, index) {
                if (value == 1) {
                    return "是";
                } else {
                    return "否";
                }
            }
        }
    ]]
    , onClickRow: function (rowIndex, rowData) {
        obj.qCRuleSourceId = rowData.id;
    }
    , onLoadSuccess: function (rowData) {
    }
});

obj.edit = function () {
    var entityId = Common_GetValue('QCDic')
    var qcDesc = encodeURIComponent(Common_GetValue('qcDesc'))
    var qcExpression = encodeURIComponent(Common_GetValue('qcExpression'))
    var errinfo = "";

    if (entityId == "" || entityId == null) {
        Sys.info("请重新选择具体病种");
        return false;
    }
    if (!qcDesc) {
        errinfo = errinfo + "描述为空!<br>";
    }
    if (errinfo) {
        $.messager.alert("错误提示", errinfo, 'info');
        return;
    }


    var qcId = Common_GetValue('qcId')
    var queryData = {};
    if (qcId == "" || qcId == null) {
        //save
    } else {
        //update
        queryData['id'] = qcId;
    }
    queryData['qcentityId'] = entityId;
    queryData['qcDesc'] = qcDesc;
    queryData['qcMemo'] = encodeURIComponent(Common_GetValue('qcMemo'));
    queryData['qcExpression'] = qcExpression;
    queryData['expDescription'] = encodeURIComponent(Common_GetValue('expDescription'));
    queryData['source'] = encodeURIComponent(Common_GetValue('source'));
    queryData['activeOnce'] = $("#activeOnce").checkbox("getValue") ? 1 : 0;
    queryData['linkCdss'] = $("#linkCdss").combobox("getValues").join("#");//多选 把数组转成字符串;
    queryData['type'] = Common_GetValue('vteType');
    queryData['isActive'] = $("#isActive").checkbox("getValue") ? 1 : 0;
    queryData['isBox'] = $("#isBox").checkbox("getValue") ? 1 : 0;
    //提交信息
    var ajax = new $ax(Sys.backendPath + "/sdc/sdcqcconfig/edit", function (res) {
        Sys.success(res.message);
        obj.entityChange();
    }, function (data) {
        Sys.error("添加失败!" + data.message + "!");
    });
    ajax.setData(queryData);
    ajax.start();
}

obj.delete = function () {
    var entityId = Common_GetValue('QCDic')
    if (entityId == "" || entityId == null) {
        Sys.info("请重新选择具体病种");
        return false;
    }
    var qcId = Common_GetValue('qcId')
    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    //提交信息
    var ajax = new $ax(Sys.backendPath + "/sdc/sdcqcconfig/delete", function (res) {
        Sys.success(res.message);
        obj.entityChange();
        obj.ClearForms();
    }, function (data) {
        Sys.error("添加失败!" + data.message + "!");
    });
    ajax.set("qcId", qcId);
    ajax.start();
}

obj.compareAllRule = function () {
    var qcId = Common_GetValue('qcId');
    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    obj.qCRuleCompare = "all";
    obj.qCChange();
}

obj.compareAllRuleSource = function () {
    var qcId = Common_GetValue('qcId');
    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    if (obj.qCRuleId == "" || obj.qCRuleId == null) {
        Sys.info("请重新选择具体规则");
        return false;
    }
    obj.qCRuleSourceCompare = "all";
    obj.qCRuleChange();
}

obj.compareYesRule = function () {
    var qcId = Common_GetValue('qcId');
    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    obj.qCRuleCompare = "yes";
    obj.qCChange();
}

obj.compareYesRuleSource = function () {
    var qcId = Common_GetValue('qcId');
    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    if (obj.qCRuleId == "" || obj.qCRuleId == null) {
        Sys.info("请重新选择具体规则");
        return false;
    }
    obj.qCRuleSourceCompare = "yes";
    obj.qCRuleChange();
}

obj.addRule = function () {
    var qcId = Common_GetValue('qcId');
    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    var index = Sys.open('新增质控条目规则', Sys.backendPath + '/sds/sdsstandrulebase/to_add', ['800px', '600px']);
    this.layerIndex = index;
}

obj.editRule = function () {
    var qcId = Common_GetValue('qcId');

    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    if (obj.qCRuleId == "" || obj.qCRuleId == null) {
        Sys.info("请重新选择具体规则");
        return false;
    }
    var index = Sys.open('质控条目规则详情', Sys.backendPath + '/sds/sdsstandrulebase/to_update/' + obj.qCRuleId, ['800px', '600px']);
    this.layerIndex = index;
}

obj.deleteRule = function () {
    var qcId = Common_GetValue('qcId');

    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    if (obj.qCRuleId == "" || obj.qCRuleId == null) {
        Sys.info("请重新选择具体规则");
        return false;
    }
    var operation = function () {
        var ajax = new $ax(Sys.backendPath + "/sds/sdsstandrulebase/delete", function (data) {
            Sys.success("删除成功!");
            obj.qCChange();
        }, function (data) {
            Sys.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set("SdsRuleBaseId", obj.qCRuleId);
        ajax.start();
    };
    Sys.confirm("是否删除该质控条目规则?", operation);
}

obj.addRuleSource = function () {
    var qcId = Common_GetValue('qcId');
    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    if (obj.qCRuleId == "" || obj.qCRuleId == null) {
        Sys.info("请重新选择具体规则");
        return false;
    }
    var index = Sys.open('新增规则取值', Sys.backendPath + '/sdc/sdcqcconfig/to_addRuleSource', ['800px', '420px']);
    this.layerIndex = index;
}

obj.editRuleSource = function () {
    var qcId = Common_GetValue('qcId');

    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    if (obj.qCRuleId == "" || obj.qCRuleId == null) {
        Sys.info("请重新选择具体规则");
        return false;
    }
    if (obj.qCRuleSourceId == "" || obj.qCRuleSourceId == null) {
        Sys.info("请重新选择具体规则取值");
        return false;
    }
    var index = Sys.open('质控条目规则取值详情', Sys.backendPath + '/sdc/sdcqcconfig/to_updateRuleSource/' + obj.qCRuleSourceId, ['800px', '420px']);
    this.layerIndex = index;
}

obj.deleteRuleSource = function () {
    var qcId = Common_GetValue('qcId');

    if (qcId == "" || qcId == null) {
        Sys.info("请重新选择具体质控条目");
        return false;
    }
    if (obj.qCRuleId == "" || obj.qCRuleId == null) {
        Sys.info("请重新选择具体规则");
        return false;
    }
    if (obj.qCRuleSourceId == "" || obj.qCRuleSourceId == null) {
        Sys.info("请重新选择具体规则取值");
        return false;
    }
    var operation = function () {
        var ajax = new $ax(Sys.backendPath + "/sdc/sdcqcconfig/cancelRuleSource", function (data) {
            Sys.success("删除成功!");
            obj.qCRuleChange();
        }, function (data) {
            Sys.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set("sdcQcRuleDatasourceId", obj.qCRuleSourceId);
        ajax.start();
    };
    Sys.confirm("是否删除该质控条目规则取值?", operation);
}

/*$('#qCRuleKey').searchbox({
    searcher:function(value){

    },
    prompt:'规则关键字'
})*/

$('#qCRuleSourceKey').searchbox({
    searcher: function (value) {

    },
    prompt: '规则取值关键字'
})

obj.import = function () {
    var index = Sys.open('导入质控项目', Sys.backendPath + '/sdc/sdcqcconfig/to_import', ['550px', '300px']);
    this.layerIndex = index;
};

function pagerFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function') {// is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {pageNumber: pageNum, pageSize: pageSize});
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}

function Common_GetValue() {
    var itmValue = '';

    if (typeof (arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#' + arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    } else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    } else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    } else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    } else if (className == 'hisui-combobox') {  //下拉框（多选下拉框没有封装）
        itmValue = $this.combobox('getValue');
    } else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    } else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.checkbox('getValue');
    } else if (className == 'hisui-radio') {  //单个单选框
        itmValue = $this.radio('getValue');
    } else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}